﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;

namespace ButsaScraperLib
{
	public sealed class TeamIdByCodeCache: IDisposable
	{
		private static volatile TeamIdByCodeCache _instance;
		private static readonly object SyncRoot = new object();

		public static TeamIdByCodeCache Instance
		{
			get
			{
				if (_instance == null)
				{
					lock (SyncRoot)
					{
						if (_instance == null)
						{
							_instance = new TeamIdByCodeCache();
						}
					}
				}
				return _instance;
			}
		}

		private const string FileName = "TeamIdByCodeCache.data";

		private readonly Dictionary<string, string> _cacheDictionary = new Dictionary<string, string>();

		private TeamIdByCodeCache()
		{
			LoadCache();
		}

		private void LoadCache()
		{
			string cachePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + FileName;
			if (File.Exists(cachePath))
			{
				string cacheFileData = File.ReadAllText(cachePath);
				//все пары ключ/значение
				string[] cachePairs = cacheFileData.Split(new[] {'#'}, StringSplitOptions.RemoveEmptyEntries);
				foreach (var cachePair in cachePairs)
				{
					string[] keyValue = cachePair.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries);
					if (!_cacheDictionary.ContainsKey(keyValue[0]))
						_cacheDictionary.Add(keyValue[0], keyValue[1]);
				}
			}
		}

		public string GetFromCache(string key)
		{
			if (_cacheDictionary.ContainsKey(key))
				return _cacheDictionary[key];
			return String.Empty;
		}

		public void AddToCache(string key, string value)
		{
			if (_cacheDictionary.ContainsKey(key))
				_cacheDictionary[key] = value;
			else
				_cacheDictionary.Add(key, value);
		}

		public void Dispose()
		{
			FlushCacheInternal();
		}

		private void FlushCacheInternal()
		{
			StringBuilder stringBuilder = new StringBuilder();
			foreach (var pair in _cacheDictionary)
			{
				stringBuilder.Append(String.Concat(pair.Key, '|', pair.Value, '#'));
			}
			string cachePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + FileName;
			File.WriteAllText(cachePath, stringBuilder.ToString());
		}

		public void FlushCache()
		{
			FlushCacheInternal();
			LoadCache();
		}
	}
}
